import { Component, OnInit } from '@angular/core';
import { GridOptions } from '@ag-grid-community/core';
import { GridConfigService } from '@core/config/grid-config.service';
import { ApiService } from '@core/services/http/api.service';
import { UserAuthService } from '@core/services/user-auth.service';
import { DatePipe } from '@angular/common';
import { ApesMessageService } from '@shared/apes/message';

@Component({
  selector: 'overtime',
  templateUrl: './overtime.component.html',
  styles: [`
    * {
      -webkit-overflow-scrolling: touch;
      -webkit-transform: translateZ(0);
    }

    ul {
      list-style: none;
    }

    ul > li {
      display: inline;
    }
  `],

})
export class OvertimeComponent implements OnInit {
  /* 按钮相关 */
  buttonBar = [
    { hide: true, style: 'default', label: '刷新', id: 'action_query', loading: false },
  ];
  title = '';
  ctx = { model: {} };

  /** Grid 相关 **/
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  rowClassRules: any;
  getContextMenuItems: any;
  height = 275 + 'px';
  posts: any;                // 获取登录角色所在门店ID

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private userAuthService: UserAuthService,
              private datePipe: DatePipe,
              private msg: ApesMessageService) {

    const userInfo = this.userAuthService.getUserInfoObj();
    if(userInfo.userAccount.post.branchObj !== undefined) {
      this.posts = userInfo.userAccount.post.branchObj.origin;
      // if(userInfo.userAccount.post.dept !== undefined) {
      //   this.posts = userInfo.userAccount.post.dept.id;
    }else {
      this.posts = null;
    }

    setTimeout(() => {
      this.queryData();
    });

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 6,
      rowHeight: 35,
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.rowClassRules = {
      // 预警
      'grid-tab-breach': function(params) {
        if (params.data.JDCS) {
          let now = params.data.JDCS;
          return now <= 0 && now > -60;
        } else {
          let now = params.data.SC;
          return now <= 0 && now > -120;
        }

      },
    };
  }

  ngOnInit() {
  }

  /**
   * 功能：按钮事件路由
   * @param data 当前按钮元数据
   */
  onEvent(data: any) {

    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.queryData();
      }
    }
  }

  queryData() {
    for (let i = 0, len = this.reportList.length; i < len; i++) {
      this.reportList[i].rowData = [];
      let api = this.reportList[i].api;
      let one = this.reportList[i].jieOver;
      let two = this.reportList[i].clzt;
      this.getTablesData(api, one, two, i);
    }
  }

  reportList = [
    {
      api: 'ipmMgzzForAppService.getMDXCCSBC',
      key: 1,
      width: '50%',
      title: '今日洗车超时补偿',
      rhj: '',
      yhj: '',
      rowData: [],
      titleList: [
        { headerName: '车牌', field: 'CPHM', width: 120 },
        { headerName: '接车人', field: 'JIECR', width: 120 },
        { headerName: '补偿金额', field: 'BCJE', width: 120 },
      ],
    },
    {
      api: 'ipmMgzzForAppService.getMDZDCSBC',
      width: '50%',
      key: 2,
      title: '今日整单超时补偿',
      rhj: '',
      yhj: '',
      rowData: [],
      titleList: [
        { headerName: '车牌', field: 'CPHM', width: 120 },
        { headerName: '接车人', field: 'JIECR', width: 120 },
        { headerName: '补偿金额', field: 'BCJE', width: 120 },
      ],
    },
    {
      api: 'ipmMdzkForAppService.getFWCS',
      width: '100%',
      title: '服务超时',
      jieOver: 1,
      clzt: '1',
      rowData: [],
      titleList: [
        { headerName: '车牌', field: 'CPHM', width: 100 },
        { headerName: '接车人', field: 'JIECR', width: 100 },
        { headerName: '接车时间', field: 'JCRQ_SJ', width: 140 },
        { headerName: '预计交车时间', field: 'YJJCRQ_SJ', width: 140 },
        { headerName: '当前节点', field: 'JD', width: 130 },
        { headerName: '超时', field: 'JDCS', width: 110, cellRenderer: this.toHour },
      ],
    },
    {
      api: 'ipmMgzzForAppService.getBPHCCS',
      width: '100%',
      title: '钣喷还车超时',
      rowData: [],
      titleList: [
        { headerName: '车牌', field: 'CPHM', width: 100 },
        { headerName: '接车人', field: 'JIECR', width: 100 },
        { headerName: '基地', field: 'JDMDMC', width: 140 },
        { headerName: '基地接车人', field: 'JIECR', width: 100 },
        { headerName: '预计交车时间', field: 'YJJCRQ_SJ', width: 130 },
        { headerName: '超时', field: 'SC', width: 110, cellRenderer: this.toHour },
      ],
    },
    {
      api: 'ipmPurchareControlReportService.queryMDPJYH',
      width: '100%',
      title: '配件要货',
      rowData: [],
      titleList: [
        { headerName: '车牌', field: 'CPHM', width: 100 },
        { headerName: '接车人', field: 'JIECR', width: 80 },
        { headerName: '配件名称', field: 'PJMC', width: 180 },
        { headerName: '采购员', field: 'RYMC', width: 80 },
        { headerName: '预计到店时间', field: 'YJDMDRQ_SJ', width: 130 },
        { headerName: '状态', field: 'ZT', width: 250 },
      ],
    },
  ];

  getTablesData(api: string, one: any, two: any, i: any) {
    let data = { 'interfaceMethod': api, 'pdata': { 'MDID': this.posts, 'FWJDCS': one, 'CLZT': two, 'MDBJ': one } };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            for (let i = 0, len = data.length; i < len; i++) {
              if (one === 1) {
                data[i]['JCRQ_SJ'] = this.timesMDHMS(data[i]['JCRQ_SJ']);
                data[i]['YJJCRQ_SJ'] = this.timesMDHMS(data[i]['YJJCRQ_SJ']);
              } else {
                data[i]['YJJCRQ_SJ'] = this.timesChange(data[i]['YJJCRQ_SJ']).slice(5, 19);
                data[i]['YJDMDRQ_SJ'] = this.timesChange(data[i]['YJDMDRQ_SJ']).slice(5, 19);
              }
            }

            if (data.array === undefined) {
              this.reportList[i].rowData = data;
            } else {
              this.reportList[i].rowData = data.array;
              this.reportList[i].rhj = data.RHJ;
              this.reportList[i].yhj = data.YHJ;
            }
            this.buttonBar[0].loading = false;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 时间戳 转换
  timesChange(times: number) {
    if (times) {
      const time = this.datePipe.transform(new Date(times), 'yyyy-MM-dd HH:mm:ss');
      return time;
    } else {
      return '';
    }
  }

  // 时间转换（配合grid调用）
  toHour(params) {
    let key = params.colDef.field;
    let data = params.data[key];

    let day = Math.floor(data / 1440);
    let hour = day >= 0
      ? Math.floor((data - (day * 1440)) / 60)
      : Math.floor(data / 60);
    let minute = hour >= 0
      ? Math.floor(data - (day * 1440) - (hour * 60))
      : Math.floor(data / 60 / 24);

    let time = '';
    if (day > 0) {
      // time = day + "天" + hour + "小时";
      time = day + '天' + hour + '小时' + minute + '分钟';
    } else if (hour > 0) {
      time = hour + '小时' + minute + '分钟';
    } else if (minute > 0) {
      time = minute + '分钟';
    }
    return time;
  }

  // 截取 月、日、时、分、秒
  timesMDHMS(key: string) {
    if (key !== undefined) {
      key = key.slice(5, 19);
    }
    return key;
  }

}
